/*
 * Project Beknyou
 * Copyright (c) 2010-2011 Saint Paul College, All Rights Reserved
 * Redistributions in source code form must reproduce the above
 * Copyright and this condition.
 * The contents of this file are subject to the GNU General Public
 * License, Version 2 (the "License"); you may not use this file
 * except in compliance with the License. A copy of the License is
 * available at http://www.opensource.org/licenses/gpl-license.php.
 */
package com.benkyou.server.listeners;

import com.benkyou.common.Player;
import com.benkyou.common.messages.ChatClientMessage;
import com.benkyou.common.messages.PlayerMessage;
import com.benkyou.common.messages.LoginMessage;
import com.benkyou.common.messages.PlayerSyncMessage;
import com.benkyou.server.GameServer;
import com.benkyou.server.listeners.attributes.PlayerAttribute;
import com.jme3.network.Filters;
import com.jme3.network.HostedConnection;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import java.util.ArrayList;

/**
 *
 * @author Austin Allman
 */
public class LoginServerListener implements MessageListener<HostedConnection> {

    private GameServer gameServer;

    public LoginServerListener(GameServer gameServer) {
        this.gameServer = gameServer;
    }

    public void messageReceived(HostedConnection source, Message m) {
        if (m instanceof LoginMessage) {
            LoginMessage loginMessage = (LoginMessage) m;
            if (gameServer.login(loginMessage.getLoginName(), loginMessage.getPassword())) {
                Player p =new Player(loginMessage.getLoginName(), loginMessage.getID(), (String) source.getAttribute("UUID"));
                System.out.println("Client connected! username: " + loginMessage.getLoginName() + " ip: " + source.getAddress() );
                gameServer.getPlayerList().add(p);
                source.getServer().getConnection(source.getId()).send(new PlayerMessage(loginMessage.getLoginName(),loginMessage.getID(),p.getUUID()));
                //gameServer.getMyServer().broadcast(Filters.notEqualTo(source), new LoginMessage(loginMessage.getLoginName(), null, loginMessage.getID(), p.getUUID()));
                  gameServer.getMyServer().broadcast(new ChatClientMessage("BenkyouServer", p.getName() + " Has joined the server!"));
                gameServer.syncPlayers();
            
            
            }
        }
    }
}
